package com.tx.axure.tkaxureweb.controller;

import com.tx.axure.tkaxureweb.constant.Constant;
import com.tx.axure.tkaxureweb.domain.entity.SUser;
import com.tx.axure.tkaxureweb.mapper.SUserMapper;
import com.tx.axure.tkaxureweb.vo.ResultVoStr;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/login_manager")
public class loginController {
    private final SUserMapper sUserMapper;

    @RequestMapping("login_in")
    public @ResponseBody
    ResultVoStr login_in(SUser sUser, HttpServletRequest request) {
        ResultVoStr resultVo = new ResultVoStr();
        sUser.setSts(true);
        if (sUserMapper.selectCount(sUser) ==1) {
            HttpSession session=request.getSession();
            SUser suser2=sUserMapper.selectOne(sUser);
            session.setAttribute(Constant.LOGIN_SESSION_KEY,suser2);
            session.setMaxInactiveInterval(24*3600);
        }else{
            resultVo.setError(1);
            resultVo.setMsg("账号或密码错误");
        }
        return resultVo;
    }

    @RequestMapping("login_out")
    public void login_out(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute(Constant.LOGIN_SESSION_KEY);
        response.sendRedirect("/list");
    }
}
